package com.example.jooqdemo.config.jooq;

import org.jooq.TransactionContext;
import org.jooq.TransactionProvider;
import org.jooq.tools.JooqLogger;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @Description: java类作用描述
 * @Author: czw
 * @date: 2018/4/27
 */
public class SpringTransactionProvider implements TransactionProvider {
    private static final JooqLogger logger = JooqLogger.getLogger(SpringTransactionProvider.class);
    // Based on the jOOQ-spring-example from https://github.com/jOOQ/jOOQ
    //  private final PlatformTransactionManager transactionManager;
    private DataSourceTransactionManager txMgr;

    //    public SpringTransactionProvider(PlatformTransactionManager transactionManager) {
//        this.transactionManager = transactionManager;
//    }
    public SpringTransactionProvider(DataSourceTransactionManager txMgr) {
        this.txMgr = txMgr;
    }

    @Override
    public void begin(TransactionContext context) {
        logger.info("Begin transaction");
        TransactionDefinition definition = new DefaultTransactionDefinition(
                TransactionDefinition.PROPAGATION_REQUIRED);
        //TransactionStatus status = this.transactionManager.getTransaction(definition);
        TransactionStatus status = this.txMgr.getTransaction(definition);
        context.transaction(new SpringTransaction(status));
    }

    @Override
    public void commit(TransactionContext ctx) {
        logger.info("commit transaction");
        this.txMgr.commit(getTransactionStatus(ctx));
    }

    @Override
    public void rollback(TransactionContext ctx) {
        logger.info("rollback transaction");
        this.txMgr.rollback(getTransactionStatus(ctx));
    }

    private TransactionStatus getTransactionStatus(TransactionContext ctx) {
        SpringTransaction transaction = (SpringTransaction) ctx.transaction();
        return transaction.getTxStatus();
    }
}
